﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using LCUV;

namespace sWarranty.WEB
{
    public partial class IncentiveClosed : System.Web.UI.Page
    {
        public string _currentUserEmpNo = "";
        public string _currentUserAuthority = "";
        public string _currentUserRegion = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            _currentUserEmpNo = GetUserLoginEmpNo();
            Session["UrltoFw"] = "IncentiveClosed.aspx";

            if (!IsPostBack)
            {
                buildDropYear();
            }
        }
        protected string GetUserLoginEmpNo()
        {
            string t = "";
            try
            {
                if (Session["UserLoginInfo"] != null)
                {
                    Entities db = new Entities();
                    var u = (TB_USER[])Session["UserLoginInfo"];
                    int _UID = Convert.ToInt32(u.Single().ID);
                    var au = from ft in db.TB_USER_LEVEL
                             where ft.USER_ID == _UID
                             select ft;
                    int _le = Convert.ToInt32(au.Single().LEVEL_ID);
                    var le = from xx in db.TB_LEVEL
                             where xx.ID == _le
                             select xx;
                    _currentUserAuthority = le.Single().REMARK;
                    _currentUserRegion = u.Single().REGION_ID;
                    if (_currentUserRegion != "00")
                    {
                        DBAction.SetSelected(dropRegion, (u.Single().REGION_ID));
                        dropRegion.Enabled = false;
                    }
                    return u.Single().EMPNO;
                }
            }
            catch (Exception)
            {
                t = "";
            }
            return t;
        }
        protected void buildtable(string p_closed_period, string p_user_region, string p_region_id, string p_option, string p_shop_code, string p_shop_name)
        {
            DataTable dt = new DataTable();
            dt = DBAction.runStore("PK_SOM_MST.PR_INCT_CLOSED_INQ", "uiroi", "p_closed_period", p_closed_period, "p_user_region", p_user_region,
                    "p_region_id", p_region_id, "p_option", p_option, "p_shop_code", p_shop_code, "p_shop_name", p_shop_name
                    , null, null, null, null, null, null
                    , null, null, null, null, null, null, null, null, null, null, null, null);
            try
            {
                if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
                {
                    MessageBox.Show(dt.Rows[0]["Error"].ToString());
                    return;
                }
            }
            catch (Exception)
            {
                //Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
            }
            if (dropOption.SelectedValue == "SUMMARY" || dropOption.SelectedValue == "MORE...")
            {
                RadGrid1.DataSource = dt;
                RadGrid1.DataBind();
            }
            else
            {
                RadGrid2.DataSource = dt;
                RadGrid2.DataBind();
            }
        }
        protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            if (dropOption.SelectedValue == "SUMMARY" || dropOption.SelectedValue == "MORE...")
            {
                RadGrid1.Visible = true;
                RadGrid2.Visible = false;
            }
            else
            {
                RadGrid1.Visible = false;
                RadGrid2.Visible = true;
            }
            if (dropYear.Items.Count > 0 && dropMonth.Items.Count > 0)
            {
                string p_user_region = _currentUserRegion;
                string p_region_id = "%";
                string p_option = dropOption.SelectedValue;
                string p_shop_code = null;
                string p_shop_name = null;

                string p_closed_period = dropYear.SelectedValue + dropMonth.SelectedValue;

                if (dropRegion.SelectedValue != "00")
                    p_region_id = dropRegion.SelectedValue;

                DataTable dt = new DataTable();
                dt = DBAction.runStore("PK_SOM_MST.PR_INCT_CLOSED_INQ", "uiroi", "p_closed_period", p_closed_period, "p_user_region", p_user_region,
                    "p_region_id", p_region_id, "p_option", p_option, "p_shop_code", p_shop_code, "p_shop_name", p_shop_name,
                     null, null, null, null, null, null
                    , null, null, null, null, null, null, null, null, null, null, null, null);
                try
                {
                    if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
                    {
                        MessageBox.Show(dt.Rows[0]["Error"].ToString());
                        return;
                    }
                }
                catch (Exception)
                {
                    //Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
                }
                RadGrid1.DataSource = dt;
            }
            else
            {
                MessageBox.Show("No Incentive closed period found");
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (dropOption.SelectedValue == "SUMMARY" || dropOption.SelectedValue == "MORE...")
            {
                RadGrid1.Visible = true;
                RadGrid2.Visible = false;
            }
            else
            {
                RadGrid1.Visible = false;
                RadGrid2.Visible = true;
            }
            if (dropYear.Items.Count > 0 && dropMonth.Items.Count > 0)
            {
                string p_user_region = _currentUserRegion;
                string p_region_id = "%";
                string p_option = dropOption.SelectedValue;
                string p_closed_period = dropYear.SelectedValue + dropMonth.SelectedValue;
                string p_shop_code = null;
                string p_shop_name = null;

                if (dropRegion.SelectedValue != "00")
                    p_region_id = dropRegion.SelectedValue;
                if (!string.IsNullOrEmpty(txtShopCode.Text.Trim()))
                    p_shop_code = txtShopCode.Text.Trim();
                if (!string.IsNullOrEmpty(txtShopName.Text.Trim()))
                    p_shop_name = txtShopName.Text.Trim();

                buildtable(p_closed_period, p_user_region, p_region_id, p_option, p_shop_code, p_shop_name);
            }
            else
            {
                MessageBox.Show("No Incentive closed period found");
            }
        }
        protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            if (e.Column is GridBoundColumn)
            {
                (e.Column as GridBoundColumn).DataFormatString = "<nobr>{0}</nobr>"; //auto width
                (e.Column as GridBoundColumn).HeaderStyle.Font.Bold = true;
                (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
 
                if ((e.Column as GridBoundColumn).HeaderText == "CLOSE_FLAG" || (e.Column as GridBoundColumn).HeaderText == "PRODUCT")
                {
                    (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                    (e.Column as GridBoundColumn).ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                }
                if ((e.Column as GridBoundColumn).HeaderText == "INCT_AMT" || (e.Column as GridBoundColumn).HeaderText == "QTY" || (e.Column as GridBoundColumn).HeaderText == "POINT" || (e.Column as GridBoundColumn).HeaderText =="WT_AMT" )
                {
                    (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                    (e.Column as GridBoundColumn).ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                }
            }
        }
        protected bool CheckDuplicate(DropDownList d, string value)
        {
            foreach (var item in d.Items)
            {
                if (value == item.ToString())
                    return true;
                else
                    return false;
            }
            return false; //ko co' item nao, thi ko trung
        }
        protected void buildDropYear()
        {
            int im = 1;
            string max="";

            Entities db = new Entities();
            var cs = from t in db.TB_CM_INCENTIVE_CLOSE_MST
                     where t.CLOSE_FLAG.ToLower() == "y"
                     orderby t.CLOSE_PERIOD descending
                     select t;
            foreach (var item in cs)
            {
                string y = item.CLOSE_PERIOD.Substring(0, 4);
                string m = item.CLOSE_PERIOD.Substring(4);
                if (im == 1)
                {
                    im += 1;
                }

                ListItem i = new ListItem();
                i.Value = y;
                i.Text = y;
                if (CheckDuplicate(dropYear, y) == false)
                    dropYear.Items.Add(i);

                if (m == "01")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "JAN";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "02")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "FEB";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "03")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "MAR";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "04")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "APR";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "05")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "MAY";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "06")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "JUN";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "07")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "JUL";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "08")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "AUG";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "09")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "SEP";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "10")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "OCT";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "01")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "JAN";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "11")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "NOV";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                } if (m == "12")
                {
                    ListItem j = new ListItem();
                    j.Value = m;
                    j.Text = "DEC";
                    if (CheckDuplicate(dropMonth, m) == false)
                        dropMonth.Items.Add(j);
                }
                DBAction.SetSelected(dropMonth, max);//DateTime.Now.Month.ToString())
            }
            if (cs.Count() > 0)
            {
                DBAction.SetSelected(dropYear, DateTime.Now.Year.ToString());
               // DBAction.SetSelected(dropMonth, m)//DateTime.Now.Month.ToString());
            }
        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            if (dropOption.SelectedValue == "SUMMARY" || dropOption.SelectedValue == "MORE...")
            {
                RadGrid1.ExportSettings.IgnorePaging = true;
                RadGrid1.ExportSettings.OpenInNewWindow = true;
                RadGrid1.ExportSettings.FileName = "incentive_summary";
                RadGrid1.MasterTableView.ExportToExcel();
            }
            else
            {
                RadGrid2.ExportSettings.IgnorePaging = true;
                RadGrid2.ExportSettings.OpenInNewWindow = true;
                RadGrid2.ExportSettings.HideStructureColumns = true; 
                RadGrid2.ExportSettings.FileName = "incentive_details";
                RadGrid2.MasterTableView.ExportToExcel();
            }
            

        }
        protected void RadGrid1_GroupsChanging(object sender, GridGroupsChangingEventArgs e)
        {
            if (e.Action == GridGroupsChangingAction.Group)
                RadGrid1.MasterTableView.GetColumnSafe(e.Expression.GroupByFields[0].FieldName).Visible = false;
            else
                if (e.Action == GridGroupsChangingAction.Ungroup)
                    RadGrid1.MasterTableView.GetColumnSafe(e.Expression.GroupByFields[0].FieldName).Visible = true;
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (_currentUserRegion != "00")
            {
                GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("REGION");
                if (column != null)
                {
                    column.Visible = false;
                }
            }
            if (e.Item is GridDataItem)
            {
                try
                {
                    GridDataItem item = (GridDataItem)e.Item;
                    double st = Convert.ToDouble(item["INCT_AMT"].Text.Replace("<nobr>", "").Replace("</nobr>", "")) ;
                    item["INCT_AMT"].Text = String.Format("{0:#,0}", st);
                }
                catch (Exception)
                {

                }

            }

        }
        protected void RadGrid2_GroupsChanging(object sender, GridGroupsChangingEventArgs e)
        {
            if (e.Action == GridGroupsChangingAction.Group)
                RadGrid2.MasterTableView.GetColumnSafe(e.Expression.GroupByFields[0].FieldName).Visible = false;
            else
                if (e.Action == GridGroupsChangingAction.Ungroup)
                    RadGrid2.MasterTableView.GetColumnSafe(e.Expression.GroupByFields[0].FieldName).Visible = true;
        }
        protected void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (_currentUserRegion != "00")
            {
                GridColumn column = RadGrid1.MasterTableView.GetColumnSafe("REGION");
                if (column != null)
                {
                    column.Visible = false;
                }
            }
            if (e.Item is GridDataItem)
            {
                try
                {
                    GridDataItem item = (GridDataItem)e.Item;
                    double st = Convert.ToDouble(item["INCT_AMT"].Text.Replace("<nobr>", "").Replace("</nobr>", "")) ;
                    item["INCT_AMT"].Text = String.Format("{0:#,0}", st);
                    
                    double wt =  Convert.ToDouble(item["WT_AMT"].Text.Replace("<nobr>", "").Replace("</nobr>", ""));
                    item["WT_AMT"].Text = String.Format("{0:#,0}", wt);
                }
                catch (Exception)
                {

                }

            }

        }
        protected void RadGrid2_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            if (dropOption.SelectedValue == "SUMMARY")
            {
                RadGrid1.Visible = true;
                RadGrid2.Visible = false;
            }
            else
            {
                RadGrid1.Visible = false;
                RadGrid2.Visible = true;
            }
            if (dropYear.Items.Count > 0 && dropMonth.Items.Count > 0)
            {
                string p_user_region = _currentUserRegion;
                string p_region_id = "%";
                string p_option = dropOption.SelectedValue;
                string p_shop_code = null;
                string p_shop_name = null;

                string p_closed_period = dropYear.SelectedValue + dropMonth.SelectedValue;

                if (dropRegion.SelectedValue != "00")
                    p_region_id = dropRegion.SelectedValue;

                DataTable dt = new DataTable();
                dt = DBAction.runStore("PK_SOM_MST.PR_INCT_CLOSED_INQ", "uiroi", "p_closed_period", p_closed_period, "p_user_region", p_user_region,
                    "p_region_id", p_region_id, "p_option", p_option, "p_shop_code", p_shop_code, "p_shop_name", p_shop_name
                    , null, null, null, null, null, null
                    , null, null, null, null, null, null, null, null, null, null, null, null);
                try
                {
                    if (dt.Rows.Count > 0 && !string.IsNullOrEmpty(dt.Rows[0]["Error"].ToString()))
                    {
                        MessageBox.Show(dt.Rows[0]["Error"].ToString());
                        return;
                    }
                }
                catch (Exception)
                {
                    //Column 'Error' does not belong to table <-- ko co' loi j va co' data , thi ko lam j
                }
                RadGrid2.DataSource = dt;
            }
            else
            {
                MessageBox.Show("No Incentive closed period found");
            }
        }
        protected void RadGrid2_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            if (e.Column is GridBoundColumn)
            {
                (e.Column as GridBoundColumn).DataFormatString = "<nobr>{0}</nobr>"; //auto width
                (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Center; 

                if ((e.Column as GridBoundColumn).HeaderText == "CLOSE_FLAG" || (e.Column as GridBoundColumn).HeaderText == "PRODUCT")
                {
                    (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                    (e.Column as GridBoundColumn).ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                }
                if ((e.Column as GridBoundColumn).HeaderText == "INCT_AMT" || (e.Column as GridBoundColumn).HeaderText == "QTY" || (e.Column as GridBoundColumn).HeaderText == "POINT" || (e.Column as GridBoundColumn).HeaderText == "WT_AMT")
                {
                    (e.Column as GridBoundColumn).HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
                    (e.Column as GridBoundColumn).ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                }
            }
        }

    }
}